from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from rest_framework import permissions, generics
from rest_framework.views import APIView
from django.db import transaction

from .models import Article
from .serializers import ArticleSerializer
from .filters import ArticleFilter
from utils.customer_modelviewset import CustomerViewSet
from utils import response_error, response_ok
from apps.system.models import Category, Log
from apps.system.serializers import CategorySerializer


# Create your views here.
class DictView(APIView):
    """获取文章标签等信息"""
    permission_classes = [permissions.IsAdminUser, ]

    def get(self, request):
        ret = {
            'article_category': CategorySerializer(
                Category.objects.filter(classify=Category.CATEGORY, type=Category.ARTICLE), many=True).data,
            'article_tags': CategorySerializer(
                Category.objects.filter(classify=Category.TAG, type=Category.ARTICLE), many=True).data
        }
        return response_ok(ret)


class ArticleViewSet(CustomerViewSet):
    """获取文章列表"""
    permission_classes = [permissions.IsAdminUser, ]
    queryset = Article.objects.filter(delete=False)
    serializer_class = ArticleSerializer

    def filter_queryset(self, queryset):
        f = ArticleFilter(self.request.data, queryset=queryset)
        return f.qs

    def perform_create(self, serializer):
        """"""
        '''
        order: post: create -> serialzier -> perform_create
        params: serialzier序列化后的数据  perform（执行、完成）
        '''
        super(ArticleViewSet, self).perform_create(serializer)
        instance = serializer.instance
        Log.objects.addLog(self.request.user, Log.INSERT, '新增文章:%id' % instance.id, serializer.initial_data)
